package ca.scotthyndman.as2haxe.dom;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import ca.scotthyndman.as2haxe.dom.visitor.IVisitor;

/**
 * Represents an object literal.
 */
public class ASObjectLiteral extends ASExpression {

	/**
	 * The "fields" structural property of this node type.
	 */
	public static final ASChildListPropertyDescriptor FIELDS_PROPERTY = new ASChildListPropertyDescriptor(
			ASObjectLiteral.class, "fields", ASObjectLiteralField.class);

	/**
	 * A list of property descriptors (element type:
	 * {@link ASPropertyDescriptor}), or null if uninitialized.
	 */
	private static final List<ASPropertyDescriptor> PROPERTY_DESCRIPTORS;

	static {
		List<Object> properyList = new ArrayList<Object>(2);
		createPropertyList(ASObjectLiteral.class, properyList);
		addProperty(FIELDS_PROPERTY, properyList);
		PROPERTY_DESCRIPTORS = reapPropertyList(properyList);
	}

	/**
	 * Returns a list of structural property descriptors for this node type.
	 * Clients must not modify the result.
	 * 
	 * @return a list of property descriptors (element type:
	 *         {@link ASPropertyDescriptor})
	 */
	public static List<ASPropertyDescriptor> propertyDescriptors() {
		return PROPERTY_DESCRIPTORS;
	}

	//
	// ======== MEMBERS
	//

	/**
	 * The fields in the object.
	 */
	private List<ASTNode> fields = new ASTNode.NodeList(FIELDS_PROPERTY);

	/**
	 * Constructs a new instance of ASObjectLiteral
	 * 
	 * @param ast
	 *            The abstract syntax tree that owns this element
	 */
	public ASObjectLiteral(AST ast) {
		super(ast);
	}

	/**
	 * @return the fields
	 */
	public List<ASTNode> getFields() {
		return fields;
	}

	//
	// ======== INTERNAL PROPERTIES
	//

	/*
	 * (omit javadoc for this method) Method declared on ASTNode.
	 */
	final List<ASTNode> internalGetChildListProperty(
			ASChildListPropertyDescriptor property) {
		if (property == FIELDS_PROPERTY) {
			return getFields();
		}
		// allow default implementation to flag the error
		return super.internalGetChildListProperty(property);
	}

	// ====== TO STRING AND VISITOR

	@Override
	public String toString() {
		StringBuffer buf = new StringBuffer("{\n");
		Iterator<ASTNode> itr = getFields().iterator();
		while (itr.hasNext()) {
			buf.append(itr.next().toString());
			if (itr.hasNext())
				buf.append(", ");
			buf.append("\n");
		}

		return buf.append("}\n").toString();
	}

	@Override
	public void accept(IVisitor as2Visitor, boolean recursive) {
		recursive = as2Visitor.visit(this);

		if (recursive) {
			for (ASTNode expr : getFields()) {
				((ASObjectLiteralField) expr).accept(as2Visitor, recursive);
			}
		}
	}
}
